package com.mjf.kxml.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.mjf.kxml.domain.ContractInfo;
import com.mjf.kxml.enums.CKApiEnum;
import com.mjf.kxml.domain.Merchant;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/6/4 10:54
 */
@Slf4j
public class CKHttpSendUtil {

    public static void main(String[] args) {
        String xml = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
            "  <soap:Body>\n" +
            "    <IFServiceResponse xmlns=\"http://www.pgxxgc.com/IF_Service\">\n" +
            "      <IFServiceReturn>\n" +
            "        &lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;Objects&gt;&lt;M_TYPE&gt;S&lt;/M_TYPE&gt;&lt;MESSAGE&gt;&lt;/MESSAGE&gt;&lt;/Objects&gt;\n" +
            "      </IFServiceReturn>\n" +
            "    </IFServiceResponse>\n" +
            "  </soap:Body>\n" +
            "</soap:Envelope>";

        CKResultVO vo = ckResult(xml);
        System.out.println(ckResult(xml).toString());

    }
    /**
     * 解析  结果
     * @param xml
     * @return
     */
    public static CKResultVO ckResult(String xml) {
        try {
            // 第一步：解析外层 SOAP
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false); // 忽略命名空间
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document outerDoc = builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));

            // 提取 IFServiceReturn 中被转义的 XML
            NodeList returnNodes = outerDoc.getElementsByTagName("IFServiceReturn");

            String escapedXml = returnNodes.item(0).getTextContent().trim();

            // 第二步：转义字符还原为真实 XML 字符
            String innerXml = escapedXml
                .replace("&lt;", "<")
                .replace("&gt;", ">")
                .replace("&amp;", "&");

            // 第三步：解析内层 XML
            Document innerDoc = builder.parse(new ByteArrayInputStream(innerXml.getBytes(StandardCharsets.UTF_8)));
            Element root = innerDoc.getDocumentElement();

            Map<String, String> resultMap = new HashMap<>();
            extractToMap(root, resultMap);

            // 转换为 Map
            String mType = resultMap.get("M_TYPE");
            String message = resultMap.get("MESSAGE");
            return CKResultVO.buildSuccess(mType, message, xml);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("请求结果解析消息失败 {} ", xml);
            return CKResultVO.buildSuccess("N", "请求结果解析消息失败", xml);
        }
    }

    // 提取内部 XML 的键值
    public static void extractToMap(Element element, Map<String, String> map) {
        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                String tag = node.getNodeName();
                String value = node.getTextContent().trim();
                map.put(tag, value);
            }
        }
    }

 /**
     * 司库数据采集合同接口
     */
    public static CKResultVO sendXml(CKApiEnum ckApiEnum, String soapXml) throws Exception {
        // 构建 SOAP XML
        String bodyXml = buildSoapXml(ckApiEnum.getMsgId(), soapXml);
        log.info(" enum info {}", ckApiEnum);
        log.info(" body xml {} ", bodyXml);
        // 发送请求
        String result = sendPost(ckApiEnum.getUrl(), bodyXml);
        log.info(" result " + result);
        return ckResult(result);
    }


    /**
     * 发送 post xml 请求
     * @param url 请求URL
     * @param soapXml  入参
     * @return
     */
    public static String sendPost(String url, String soapXml) {
        // 发送 POST 请求
        try {
            HttpResponse response = HttpRequest.post(url)
                .header("Content-Type", "text/xml;charset=UTF-8")
                .body(soapXml)
                .timeout(10000) // 超时时间可设置
                .execute();
            return response.body();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    public static String buildSoapXml(String sMsgID, String cdataXml) throws Exception {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // 创建文档
        Document doc = docBuilder.newDocument();

        // Envelope
        Element envelope = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "soapenv:Envelope");
        envelope.setAttribute("xmlns:if", "http://www.pgxxgc.com/IF_Service");
        doc.appendChild(envelope);

        // Header
        Element header = doc.createElement("soapenv:Header");
        envelope.appendChild(header);

        // Body
        Element body = doc.createElement("soapenv:Body");
        envelope.appendChild(body);

        // IFService
        Element ifService = doc.createElement("if:IFService");
        body.appendChild(ifService);

        // sMsgID
        Element msgID = doc.createElement("if:sMsgID");
        msgID.setTextContent(sMsgID);
        ifService.appendChild(msgID);

        // sContent 包含 CDATA
        Element sContent = doc.createElement("if:sContent");
        ifService.appendChild(sContent);

        CDATASection cdata = doc.createCDATASection(cdataXml);
        sContent.appendChild(cdata);

        // 转换为字符串输出
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));

        return writer.toString();
    }
    /**
     * 为空时，返回空字符串
     * @param str
     * @return
     */
    public static String jurEmpty(String str) {
        if (StrUtil.isNotBlank(str)) {
            return str;
        }
        return "";
    }


}
